﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_TOOL.Tool.UserControls;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.Common.ValueObject;

namespace ERP_RORZE_TOOL.Tool.Forms
{
    public partial class frm_BrokenEdit : DevExpress.XtraEditors.XtraForm
    {
        public int Id;
        public DateTime Date;
        public string ToolId;
        public string MachineId;
        public string MistakeId;
        public string StatusName;
        public string LossNo;
        public string PartNo;
        public int Quantity;
        public string ProcessStatus;
        public string Rotate;
        public string StandardSpeed;
        public string RealitySpeed;
        public string Process;
        public string ToKind;
        public string Note;

        private ucBroken parent;
        private DataTable dt = new DataTable();
        //private DataTable dtToKind = new DataTable();
        private bool firstLoadDone;

        public frm_BrokenEdit(ucBroken fBroken)
        {
            InitializeComponent();
            btAdd.Image = ERP_RORZE_TOOL.Properties.Resources.accept;
            btCancel.Image = ERP_RORZE_TOOL.Properties.Resources.cancel;
            parent = fBroken;
            this.CancelButton = this.btCancel;
        }

        private void XtraForm1_Load(object sender, EventArgs e)
        {
            dtpTDate.Value = Date;
            txtQuantity.Text = Quantity.ToString();
            txtLossNo.Text = LossNo.ToString();
            txtStandardSpeed.Text = StandardSpeed;
            txtRealitySpeed.Text = RealitySpeed;

            BindDataTool();
            BindDataMistake();
            BindDataMachine();
            BindDataStatus();
            BindDataPart();
            BindDataProcessStatus();
            BindDataRotate();
            BindDataToKind();
            memoTNote.Text = Note;

            if (Process == ToolConstants.Configuration.ProcessStatus.TrueStr)
            {
                rdChangekind.Checked = true;
            }
            else
            {
                rdDelete.Checked = true;
            }

        }

        private void btTAdd_Click_1(object sender, EventArgs e)
        {
            UpdateTool();
        }

        private void btTCancel_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        private void rdDelete_CheckedChanged(object sender, EventArgs e)
        {
            lblSelecTool.Enabled = false;
            cmbToKind.SelectedItem = cmbToKind.Items[0];
            cmbToKind.Enabled = false;
        }

        private void rdChangekind_CheckedChanged(object sender, EventArgs e)
        {
            lblSelecTool.Enabled = true;
            cmbToKind.Enabled = true;
        }

        private void cmbMachine_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbMachine.SelectedItem != cmbMachine.Items[0] && firstLoadDone)
            {
                string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
                string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.SelectedValue + "' and " + ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.SelectedValue + "'";
                string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
                string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

                int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);

                if (number == 0)
                    MessageBox.Show(string.Format(ToolConstants.Message.Broken.MachineNotBorrow, cmbMachine.SelectedValue, cmbToolID.SelectedValue), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                else
                {
                    MessageBox.Show(string.Format(ToolConstants.Message.Broken.MachineBorrow, cmbMachine.SelectedValue, cmbToolID.SelectedValue, number.ToString()), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        protected override bool ProcessKeyPreview(ref Message m)
        {
            if (m.Msg == 0x0100 && (int)m.WParam == 13)
            {
                this.ProcessTabKey(true);
            }
            return base.ProcessKeyPreview(ref m);
        }
        #region Private methods

        private bool GetDataTool(Broken o)
        {
            #region Check valid

            if (Utilities.IsNullOrEmpty(dtpTDate.Value.ToString()))
            {
                MessageBox.Show(ToolConstants.Message.Broken.DateCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbToolID.SelectedValue) || cmbToolID.SelectedItem == cmbToolID.Items[0])
            {
                MessageBox.Show(ToolConstants.Message.Broken.ToolIDCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbMachine.SelectedValue) || cmbMachine.SelectedItem == cmbMachine.Items[0])
            {
                MessageBox.Show(ToolConstants.Message.Broken.MachineCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbMistake.SelectedValue) || cmbMistake.SelectedItem == cmbMistake.Items[0])
            {
                MessageBox.Show(ToolConstants.Message.Broken.MistakeCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbStatus.SelectedValue) || cmbStatus.SelectedItem == cmbStatus.Items[0])
            {
                MessageBox.Show(ToolConstants.Message.Broken.StatusCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(txtLossNo.Text.Trim()))
            {
                MessageBox.Show(ToolConstants.Message.Broken.LossNoCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbPart.SelectedValue) || cmbPart.SelectedItem == cmbPart.Items[0])
            {
                MessageBox.Show(ToolConstants.Message.Broken.PartCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(txtQuantity.Text.Trim()))
            {
                MessageBox.Show(ToolConstants.Message.Broken.QuantityCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (int.Parse(txtQuantity.Text) <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.QuantityMustGreaterZero, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtQuantity.Focus();
                return false;

            }

            if (int.Parse(txtQuantity.Text) > 0)
            {
                string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
                string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.SelectedValue + "' and " + ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.SelectedValue + "'";
                string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
                string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

                int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);


                if ((cmbToolID.SelectedValue.ToString() != ToolId) && number < int.Parse(txtQuantity.Text))
                {
                    MessageBox.Show(string.Format(ToolConstants.Message.Broken.WrongQuantity, cmbMachine.SelectedValue, number.ToString(), txtQuantity.Text), ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtQuantity.Focus();
                    return false;
                }
                else
                    if ((cmbToolID.SelectedValue.ToString() == ToolId) && (int.Parse(txtQuantity.Text) - Quantity) > number)
                    {
                        MessageBox.Show(string.Format(ToolConstants.Message.Broken.WrongQuantity2, Quantity.ToString(), txtQuantity.Text, cmbToolID.SelectedValue.ToString(), cmbMachine.SelectedValue, number.ToString()), ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtQuantity.Focus();
                        return false;
                    }

            }

            if (Utilities.IsNullOrEmpty(cmbProcessStatus.SelectedValue) || cmbProcessStatus.SelectedItem == cmbProcessStatus.Items[0])
            {
                MessageBox.Show(ToolConstants.Message.Broken.ProcessStatusCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbRotate.SelectedValue) || cmbRotate.SelectedItem == cmbRotate.Items[0])
            {
                MessageBox.Show(ToolConstants.Message.Broken.RotateCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            //if(Utilities.IsNullOrEmpty(txtStandardSpeed.Text.Trim()))
            //{
            //    MessageBox.Show(ToolConstants.Message.Broken.StandardSpeedCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return false;
            //}

            //if(Utilities.IsNullOrEmpty(txtRealitySpeed.Text.Trim()))
            //{
            //    MessageBox.Show(ToolConstants.Message.Broken.RealitySpeedCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    return false;
            //}

            if (rdChangekind.Checked)
            {

                if (Utilities.IsNullOrEmpty(cmbToKind.SelectedValue) || cmbToKind.SelectedItem == cmbToKind.Items[0])
                {
                    MessageBox.Show(ToolConstants.Message.Broken.ToKindCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            #endregion

            o.ID = Id;
            o.Date = dtpTDate.Value;
            o.ToolID = cmbToolID.SelectedValue.ToString();
            o.MachineID = cmbMachine.SelectedValue.ToString();
            o.MistakeID = cmbMistake.SelectedValue.ToString();
            o.StatusName = cmbStatus.SelectedValue.ToString();
            o.LossNo = txtLossNo.Text;
            o.PartNo = cmbPart.SelectedValue.ToString();
            o.Quantity = int.Parse(txtQuantity.Text);
            o.ProcessStatusID = cmbProcessStatus.SelectedValue.ToString();
            o.RotateID = cmbRotate.SelectedValue.ToString();
            o.StandardSpeed = txtStandardSpeed.Text;
            o.RealitySpeed = txtRealitySpeed.Text;
            if (rdChangekind.Checked)
            {
                o.Process = ToolConstants.Configuration.ProcessStatus.TrueStr;
                o.ToKind = cmbToKind.SelectedValue.ToString();
            }
            else
            {
                o.Process = ToolConstants.Configuration.ProcessStatus.FalseStr;
                o.ToKind = "";

            }
            o.Note = memoTNote.Text;

            return true;
        }

        private void BindDataTool()
        {
            ToolHelper helper = new ToolHelper(new Tools());
            dt = helper.GetAllByToolType();
            DataRow row = dt.NewRow();


            row[ToolConstants.Entities.Tool.FieldName.FullName] = "Select...";
            row[ToolConstants.Entities.Tool.FieldName.ToolID] = null;
            dt.Rows.InsertAt(row, 0);

            cmbToolID.DataSource = dt;
            cmbToolID.DisplayMember = ToolConstants.Entities.Tool.FieldName.FullName;
            cmbToolID.ValueMember = ToolConstants.Entities.Tool.FieldName.ToolID;

            cmbToolID.SelectedValue = ToolId;
            if (cmbToolID.SelectedItem == null)
            {
                cmbToolID.SelectedItem = cmbToolID.Items[0];
            }

        }

        private void BindDataMistake()
        {
            MistakeHelper helper = new MistakeHelper(new Mistake());
            DataTable dt = helper.GetAll();
            DataRow row = dt.NewRow();

            row[ToolConstants.Entities.Mistake.FieldName.FullName] = "Select...";
            row[ToolConstants.Entities.Mistake.FieldName.MistakeID] = null;
            dt.Rows.InsertAt(row, 0);

            cmbMistake.DataSource = dt;
            cmbMistake.DisplayMember = ToolConstants.Entities.Mistake.FieldName.FullName;
            cmbMistake.ValueMember = ToolConstants.Entities.Mistake.FieldName.MistakeID;

            cmbMistake.SelectedValue = MistakeId;
            if (cmbMistake.SelectedItem == null)
            {
                cmbMistake.SelectedItem = cmbMistake.Items[0];
            }
        }

        private void BindDataMachine()
        {
            MachineHelper helper = new MachineHelper(new Machine());
            DataTable dt = helper.GetAll();
            DataRow row = dt.NewRow();

            row[ToolConstants.Entities.Machine.FieldName.FullName] = "Select...";
            row[ToolConstants.Entities.Machine.FieldName.MachineID] = null;
            dt.Rows.InsertAt(row, 0);

            cmbMachine.DataSource = dt;
            cmbMachine.DisplayMember = ToolConstants.Entities.Machine.FieldName.FullName;
            cmbMachine.ValueMember = ToolConstants.Entities.Machine.FieldName.MachineID;
            cmbMachine.SelectedValue = MachineId;
            if (cmbMachine.SelectedItem == null)
            {
                cmbMachine.SelectedItem = cmbMachine.Items[0];
            }
            firstLoadDone = true;
        }

        private void BindDataStatus()
        {
            ToolStatusHelper helper = new ToolStatusHelper(new ToolStatus());
            DataTable dt = helper.GetAll();
            DataRow row = dt.NewRow();

            row[ToolConstants.Entities.ToolStatus.FieldName.StatusName] = "Select...";
            dt.Rows.InsertAt(row, 0);

            cmbStatus.DataSource = dt;
            cmbStatus.DisplayMember = ToolConstants.Entities.ToolStatus.FieldName.StatusName;
            cmbStatus.ValueMember = ToolConstants.Entities.ToolStatus.FieldName.StatusName;
            cmbStatus.SelectedValue = StatusName;
            if (cmbStatus.SelectedItem == null)
            {
                cmbStatus.SelectedItem = cmbStatus.Items[0];
            }
        }

        private void BindDataPart()
        {
            PartHelper helper = new PartHelper(new Part());
            DataTable dt = helper.GetAll();
            DataRow row = dt.NewRow();

            row[ToolConstants.Entities.Part.FieldName.FullName] = "Select...";
            row[ToolConstants.Entities.Part.FieldName.PartNo] = DBNull.Value;
            dt.Rows.InsertAt(row, 0);

            cmbPart.DataSource = dt;
            cmbPart.DisplayMember = ToolConstants.Entities.Part.FieldName.FullName;
            cmbPart.ValueMember = ToolConstants.Entities.Part.FieldName.PartNo;
            cmbPart.SelectedValue = PartNo;
            if (cmbPart.SelectedItem == null)
            {
                cmbPart.SelectedItem = cmbPart.Items[0];
            }
        }

        private void BindDataProcessStatus()
        {
            ProcessStatusHelper helper = new ProcessStatusHelper(new ProcessStatus());
            DataTable dt = helper.GetAll();
            DataRow row = dt.NewRow();

            row[ToolConstants.Entities.ProcessStatus.FieldName.FullName] = "Select...";
            row[ToolConstants.Entities.ProcessStatus.FieldName.ProcessStatusID] = null;
            dt.Rows.InsertAt(row, 0);

            cmbProcessStatus.DataSource = dt;
            cmbProcessStatus.DisplayMember = ToolConstants.Entities.ProcessStatus.FieldName.FullName;
            cmbProcessStatus.ValueMember = ToolConstants.Entities.ProcessStatus.FieldName.ProcessStatusID;
            cmbProcessStatus.SelectedValue = ProcessStatus;
            if (cmbProcessStatus.SelectedItem == null)
            {
                cmbProcessStatus.SelectedItem = cmbProcessStatus.Items[0];
            }
        }

        private void BindDataRotate()
        {
            RotateHelper helper = new RotateHelper(new Rotate());
            DataTable dt = helper.GetAll();
            DataRow row = dt.NewRow();

            row[ToolConstants.Entities.Rotate.FieldName.FullName] = "Select...";
            row[ToolConstants.Entities.Rotate.FieldName.RotateID] = null;
            dt.Rows.InsertAt(row, 0);

            cmbRotate.DataSource = dt;
            cmbRotate.DisplayMember = ToolConstants.Entities.Rotate.FieldName.FullName;
            cmbRotate.ValueMember = ToolConstants.Entities.Rotate.FieldName.RotateID;
            cmbRotate.SelectedValue = Rotate;
            if (cmbRotate.SelectedItem == null)
            {
                cmbRotate.SelectedItem = cmbRotate.Items[0];
            }

            //try
            //{
            //	cmbRotate.SelectedValue = Rotate;
            //	if(cmbRotate.SelectedItem == null)
            //	{
            //		cmbRotate.SelectedItem = cmbRotate.Items[0];
            //	}
            //}
            //catch (Exception)
            //{
            //	cmbRotate.SelectedItem = cmbRotate.Items[0];
            //}
        }

        private void BindDataToKind()
        {
            DataRow row;

            if (dt.Rows.Count == 0)
            {
                ToolHelper helper = new ToolHelper(new Tools());
                dt = helper.GetAll();
                row = dt.NewRow();

                row[ToolConstants.Entities.Tool.FieldName.FullName] = "Select...";
                row[ToolConstants.Entities.Tool.FieldName.ToolID] = null;
                dt.Rows.InsertAt(row, 0);

                cmbToKind.DataSource = dt;
                cmbToKind.DisplayMember = ToolConstants.Entities.Tool.FieldName.FullName;
                cmbToKind.ValueMember = ToolConstants.Entities.Tool.FieldName.ToolID;

                cmbToKind.SelectedValue = ToKind;
                if (cmbToKind.SelectedItem == null)
                {
                    cmbToKind.SelectedItem = cmbToKind.Items[0];
                }
            }
            else
            {
                row = dt.NewRow();
                
                row[ToolConstants.Entities.Tool.FieldName.FullName] = "Select...";
                row[ToolConstants.Entities.Tool.FieldName.ToolID] = null;

                cmbToKind.DataSource = dt;
                cmbToKind.DisplayMember = ToolConstants.Entities.Tool.FieldName.FullName;
                cmbToKind.ValueMember = ToolConstants.Entities.Tool.FieldName.ToolID;

                cmbToKind.SelectedValue = ToKind;
                if (cmbToKind.SelectedItem == null)
                {
                    cmbToKind.SelectedItem = cmbToKind.Items[0];
                }
            }
        }

        private void UpdateTool()
        {
            BrokenHelper helper = new BrokenHelper(new Broken());
            if (GetDataTool(helper.ValueObject))
            {



                if (helper.Update() > 0)
                {

                    if (!Utilities.MessageConfirmationYesNo(ToolConstants.Message.UpdateSuccessAndQuestion))
                    {
                        this.Close();
                    }
                }
                else
                {

                    Utilities.MessageErrorOk(ToolConstants.Message.UpdateFailed);
                }

                parent.BindDatatoGrid();

            }
        }

        #endregion

        
    }
}